package com.example.shop_management.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.shop_management.entity.Log;
import com.example.shop_management.mapper.LogMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Resource
    private LogMapper logMapper;

    ThreadLocal<Long> startTime =new ThreadLocal<>();

    @Pointcut("execution(public * com.example.shop_management.controller..*.*(..))")
    public void controllerMethod() {
    }

    @Around("controllerMethod()")
    public Object myLogger(ProceedingJoinPoint pjp) throws Throwable {
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = pjp.getSignature();
        String classNmae = signature.getDeclaringTypeName();
        String methodName = signature.getName();
        Object[] array = pjp.getArgs();
//        ObjectMapper mapper = new ObjectMapper();
        //执行前
        log.info("调用前:{}:{},传递的参数为:{}",classNmae,methodName,array);
        log.info("URL:{}",request.getRequestURL().toString());
        log.info("IP地址:{}",request.getRemoteAddr());
        //执行
        Object obj = pjp.proceed();
        //执行后
        log.info("调用后:{}:{},传递的参数为:{}",classNmae,methodName, obj);
        long l = System.currentTimeMillis() - startTime.get();
        log.info("耗时:{}ms",l);
        Log log = new Log();
        log.setUrl(request.getRequestURL().toString());
        log.setArg0(Arrays.toString(array));
        log.setClassName(classNmae);
        log.setMethodName(methodName);
        log.setUseTime(l);
        logMapper.insert(log);
        return obj;
    }





}
